/**
 * 广寒宫
 * 网址:www.guanghangong.xyz
 */
package org.moon.framework.autoconfigure.secure;

import javax.servlet.http.HttpServletRequest;

import lombok.extern.slf4j.Slf4j;
import org.moon.framework.autoconfigure.exception.domain.MoonException;
import org.moon.framework.autoconfigure.secure.domain.AuthInfo;
import org.moon.framework.autoconfigure.utils.Func;
import org.moon.framework.autoconfigure.MoonConstants;
import org.moon.framework.autoconfigure.cache.CacheService;
import org.moon.framework.autoconfigure.config.SpringContextConfig;
import org.moon.framework.autoconfigure.utils.JsonUtils;
import org.moon.framework.autoconfigure.utils.SecurityUtils;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;

/**
 * 权限工具类
 * @author moon
 */
@Slf4j
public class AuthUtils {
	
	/**
	 * 从请求头或请求参数里获取信息,优先从请求参数
	 * @return
	 */
	public static String getValueFromHeadOrParams(String name) {
		HttpServletRequest request = Func.getRequest();
		if(request==null){
			return null;
		}
		String v =  request.getParameter(name);
		if(Func.isBlank(v)) {
			return request.getHeader(name);
		}
		return v;
	}
	
	/**
	 * 获取租户编码
	 * @return
	 */
	public static String getTenantCode() {
		return getValueFromHeadOrParams(MoonConstants.HEADER_TENANT_CODE);
	}

	/**
	 * 获取请求id
	 */
	public static String getRequestId(){
		return getValueFromHeadOrParams(MoonConstants.HEADER_REQUEST_ID);
	}

	/**
	 * 获取请求来源
	 */
	public static String getRequestFrom(){
		return getValueFromHeadOrParams(MoonConstants.REQUEST_FROM);
	}

	/**
	 * 获取header里的token
	 */
	public static String getToken(){
		return getValueFromHeadOrParams(MoonConstants.HEADER_ACCESS_TOKEN);
	}

	/**
	 * 获取当前登录用户信息(从token解析)
	 */
	public static AuthInfo getAuthInfo(){
		String authorities = getValueFromHeadOrParams(MoonConstants.JWT_AUTHORITIES_KEY);;
		if(Func.isBlank(authorities)){
			log.error("缺少token信息");
			return new AuthInfo();
		}
		try {
			authorities = URLDecoder.decode(authorities,"UTF-8");
			return JsonUtils.str2obj(authorities,AuthInfo.class);
		}catch (Exception e){
			log.error("token信息解析失败");
			return new AuthInfo();
		}
	}

	/**
	 * 获取当前登录的用户id
	 */
	public static Integer getCurrentUserId(){
		return getAuthInfo().getId();
	}

	/**
	 * 获取当前登录的用户名
	 */
	public static String getCurrentUserName() {
		return getAuthInfo().getUserName();
	}

	/**
	 * 获取当前登录用户的角色编码
	 * @return
	 */
	public static List<String> getRoleCodes(){
		return getAuthInfo().getRoleCodes();
	}


	/**
	 * 当前登录的用户是否是admin
	 */
	public static boolean isAdmin() {
		List<String> roleCodes = getRoleCodes();
		return Func.isNotEmpty(roleCodes) && roleCodes.contains(MoonConstants.ADMIN_CODE);
	}
}